from modelscope import AutoModelForCausalLM, AutoTokenizer

import time
import builtins

start = time.perf_counter()
_original_print = builtins.print

model_name = "D:\\work\\program\\pytorch_models\\Qwen2.5-3B-Instruct"

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# prompt = "你是待办提醒助手,帮我识别用户输入是否是一个待办或提醒,以{\"code\": \"true或false\",\"response\": {\"desc\": \"输入的原文\",\"time\": \"提醒时间\"}},模板样例{\"code\": \"true\",\"response\": {\"desc\": \"明天晚上8点给客户打电话\",\"time\": \"明天晚上8点\"}},返回严格的json格式,不要有其它多余字符。以下是用户输入:开会"
# prompt = "你是待办提醒助手,帮我识别用户输入是否是一个待办或提醒,以{\"code\": \"true或false\",\"response\": {\"desc\": \"输入的原文\",\"time\": \"提醒时间\"}},模板样例{\"code\": \"true\",\"response\": {\"desc\": \"明天晚上8点给客户打电话\",\"time\": \"明天晚上8点\"}},返回严格的json格式,不要有其它多余字符。以下是用户输入:周五上午10点团建"
prompt = ("你是待办提醒助手,帮我识别用户输入是否是一个待办或提醒,以"
          "{\"code\": \"true或false\",\"response\": {\"desc\": \"输入的原文\",\"time\": \"提醒时间\"}},"
          "模板样例{\"code\": \"true\",\"response\": {\"desc\": \"明天晚上8点给客户打电话\",\"time\": \"明天晚上8点\"}},"
          "返回严格的json格式,不要有其它多余字符。以下是用户输入:周五上午10点团建")
messages = [
    {"role": "system", "content": "你是智能助手！"},
    {"role": "user", "content": prompt},
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=512,
    temperature=0.3,          # 控制生成随机性
    repetition_penalty=1.1   # 防止重复
)
generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]

response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]

print(response)
elapsed = time.perf_counter() - start
_original_print(f"[耗时] print执行时间: {elapsed:.6f}秒")